import { NextApiRequest, NextApiResponse } from 'next'
import {withIronSessionApiRoute} from 'iron-session/next'
import {prepareConnection} from 'db/index'
import { User,Tag } from 'db/entity/index'
import {ironOptions} from 'config/index'
import { ISession} from 'pages/api/index'
import { EXCEPTION_USER,EXCEPTION_TAG } from 'pages/api/config/codes'

export default withIronSessionApiRoute(follow,ironOptions)

async function follow(req: NextApiRequest, res: NextApiResponse) {
    const sesssion: ISession = req.session
    const {userId} = sesssion
    const {tagId,type} = req?.body
    // 连接数据库
    const db = await prepareConnection()
    const tagRepo = db.getRepository(Tag)
    const userRepo = db.getRepository(User)
    // 查询用户
    const user = await userRepo.findOne({
        where: { id: userId },
    })
    // 查询标签
    const tag = await tagRepo.findOne({
        relations: ['users'],
        where: { id: tagId },
    })
    // 如果查询不到用户，则返回错误
    if(!user){
        res?.status(200).json({...EXCEPTION_USER?.NOT_LOGIN})
        return
    }

    if(tag?.users){
      if(type === 'follow'){
        tag.users = tag?.users.concat([user])
        tag.follow_count = tag?.follow_count + 1
      }else if(type === 'unfollow'){
        tag.users = tag?.users.filter((item: any) => item.id !== userId)
        tag.follow_count = tag?.follow_count - 1
      }
    }



    if(tag){
        const resTag = await tagRepo?.save(tag)
        res?.status(200).json({code:0,msg:'',data:resTag})
    }else{
        res?.status(200).json({...EXCEPTION_TAG?.FOLLOW_FAILED})
    }

}